
*List of outputs:
*Main text:
*amces4.pdf
*density_structural_horizontal.pdf
*income_decay_rating.pdf
*all_decay_rating.pdf

*table_wtp_deltamethod_all_rating.tex
*table_rw_deltamethod_rating.tex

*************************************
*Appendix:
*consistency_choice_rating_deciles_rd.pdf
*amcesrobust
*amcesrobust2
*density_structural_horizontal_appendix2.pdf
*density_structural_horizontal_appendix.pdf
*percentiles.pdf

*balance_covars_brasil.tex
*balance_covars_france.tex
*balance_covars_us.tex
*table_wtp_deltamethod_all_choice.tex
*table_rw_deltamethod_choice.tex
*balancer_antiprodem_brasil.tex
*balancer_antiprodem_france.tex
*balancer_antiprodem_us.tex


clear all


use pnas_data_dataverse.dta, replace


*Set a global to the folders where you want to save the results (change it to yours). 
global output2 "/Users/andreuarenasjal/Dropbox/Apps/Overleaf/value of democracy/"
global output3 "/Users/andreuarenasjal/Dropbox/Apps/Overleaf/PNAS TEMPLATE - value of democracy/"


********************************************************************************
***********************************SAMPLE***************************************
********************************************************************************

*This identifies inconsistencies between ratings and choices across the survey length distribution

foreach var in rating choice{
gen `var'aux1=`var' if pos==1
egen m`var'aux1=max(`var'aux1), by(set numericalid)

gen `var'aux2=`var' if pos==2
egen m`var'aux2=max(`var'aux2), by(set numericalid)

gen `var'_other=m`var'aux1 if pos==2
replace `var'_other=m`var'aux2 if pos==1
drop `var'aux1 m`var'aux1
}

gen error=1 if rating>rating_other & choice==0
replace error=0 if rating<=rating_other & choice==0

egen mean_error=mean(error), by(numericalid)
bys numericalid: gen auxerror=_n
xtile Duration_Decile=duration, n(10)

gen delta=rating-rating_other
binscatter choice delta, by(Duration_Decile) linetype(connect) xtitle("Rating Difference between pairs of alternatives") ytitle("Choice") subtitle("Choices as a function of rating differences, by survey length decile") note("Inconsistencies: positive rating difference and no choice, or negative rating difference and choice." "Decile 1 = lowest length, Decile 10, highest length.")  legend(label (1 "Decile 1") label(2 "Decile 2") label(3 "Decile 3") label(4 "Decile 4") label(5 "Decile 5") label(6 "Decile 6") label(7 "Decile 7") label(8 "Decile 8") label (9 "Decile 9") label (10 "Decile 10"))

*Paper plot: Fig. S3
quietly graph export "${output2}plots/final_consistency_choice_rating_deciles_rd.png", as(png) width(1250) replace
quietly graph export "${output2}plots/final_consistency_choice_rating_deciles_rd.pdf", as(pdf) replace
drop rating_other choice_other delta Duration_Decile mean_error error 
drop if duration<600

 

 
********************************************************************************
*******************************ANALYSIS*****************************************
********************************************************************************
*Create normalized variables (normalized by the mean of country income)
gen satr1_cont_ppp=atr1_cont_ppp/1.271186 if brasil==1
gen satr2_cont_ppp=atr2_cont_ppp/1.271186 if brasil==1
replace satr1_cont_ppp=atr1_cont_ppp/4.109589  if france==1
replace satr2_cont_ppp=atr2_cont_ppp/4.109589  if france==1
replace satr1_cont_ppp=atr1_cont_ppp/6 if us==1
replace satr2_cont_ppp=atr2_cont_ppp/6 if us==1

*Create auxiliary locals for tables USING ESTTAB
*z indexes the specification, the second number the fixed effect
forval z=1(1)2{
local fe`z'_1="$\checkmark$"
}
forval z=2(1)2{
local fe`z'_2="$\checkmark$"
}


*Define lists that we use in the loops
global countries all brasil france us
global depvars rating choice
global atrlevels satr1_cont_ppp satr2_cont_ppp
global fe1 pos set 
global fe2 numericalid pos set set#numericalid

local depvar0 Rating
local depvar1 Choice
local spec1 Levels
local country2 Brazil
local country3 France
local country4 US
local country1 All


********************************************************************************
*We estimate AMCEs in this loop (by country, specification, and dep. var
********************************************************************************

eststo clear
*For each country
gen all=1
local countryc=0
foreach country in all brasil france us {
local countryc= `countryc'+1

*For each sets of fixed effects specifications
local i=0
foreach fixedeff in fe1 fe2{
local i=`i'+1

*For each dependent variable (choice, rating)
local dv=-1
foreach depvar in $depvars{
local dv=`dv'+1

*Here we'll do everything for income in ppp dollars vs. normalized income
*We define globals with text that we will use repeatedly in various regressions to make the code more readable

*This is the denominator for the weight of democracy: the sum of absolute values of all coefficients.
*First, for PPP thousands, then, for normalized
global denom (abs(_b[democracy])+abs(_b[public_health])+ abs(_b[effort]) +abs(_b[equal_society])+abs(_b[satr1_cont_ppp])+abs(_b[satr2_cont_ppp]))
global denom2 (abs(_b[democracy])+abs(_b[public_health])+ abs(_b[effort]) +abs(_b[equal_society])+abs(_b[atr1_cont_ppp])+abs(_b[atr2_cont_ppp]))
*This is the denominator for the willingness to pay
*First, for PPP thousands, then, for normalized
global wtpdenom (0.01*abs(_b[satr1_cont_ppp]))
global wtpdenom2 (abs(_b[atr1_cont_ppp]))

*Now is the list of measures that we want: wtp and weight of each component (the various ratios)
*This does it for normalized income
global auxbootstrap (ratio1: (abs(_b[democracy]))/ $denom )  (wtp1: (_b[democracy])/ $wtpdenom )  /*
*/ (ratio2: (abs(_b[public_health]))/ $denom ) (wtp2: (_b[public_health])/ $wtpdenom ) /*
*/ (ratio3: (abs(_b[effort]))/ $denom ) (wtp3: (_b[effort])/ $wtpdenom ) /*
*/ (ratio4: (abs(_b[equal_society]))/ $denom ) (wtp4: (_b[equal_society])/ $wtpdenom )/*
*/ (ratio5: (abs(_b[satr2_cont_ppp]))/ $denom ) (wtp5: (.1*_b[satr2_cont_ppp])/ $wtpdenom ) /*
*/ (ratio6: (abs(_b[satr1_cont_ppp]))/ $denom ) (wtp6: (_b[satr1_cont_ppp])/ $wtpdenom ), post

*This does it for ppp dollars, for which we need adjust country income for the ppp when dividing by individual income
global auxbootstrap1 (wtp1: (_b[democracy])/ $wtpdenom2 ), post

global auxbootstrap2 (wtp1: (_b[democracy])/ $wtpdenom2 )  /*
*/   (wtp2: (_b[public_health])/ $wtpdenom2 ) /*
*/   (wtp3: (_b[effort])/ $wtpdenom2 ) /*
*/   (wtp4: (_b[equal_society])/ $wtpdenom2 )/*
*/   (wtp5: (0.1271186*_b[atr2_cont_ppp] )/ $wtpdenom2 ) /*
*/   (wtp6: (_b[atr1_cont_ppp])/ $wtpdenom2 ), post

global auxbootstrap3 (wtp1: (_b[democracy])/ $wtpdenom2 )  /*
*/   (wtp2: (_b[public_health])/ $wtpdenom2 ) /*
*/   (wtp3: (_b[effort])/ $wtpdenom2 ) /*
*/   (wtp4: (_b[equal_society])/ $wtpdenom2 )/*
*/   (wtp5: (.4109589*_b[atr2_cont_ppp])/ $wtpdenom2 ) /*
*/   (wtp6: (_b[atr1_cont_ppp])/ $wtpdenom2 ), post

global auxbootstrap4 (wtp1: (_b[democracy])/ $wtpdenom2 )  /*
*/   (wtp2: (_b[public_health])/ $wtpdenom2 ) /*
*/   (wtp3: (_b[effort])/ $wtpdenom2 ) /*
*/   (wtp4: (_b[equal_society]) / $wtpdenom2 )/*
*/   (wtp5: (.6*_b[atr2_cont_ppp]) / $wtpdenom2 ) /*
*/   (wtp6: (_b[atr1_cont_ppp])/ $wtpdenom2 ), post




*We first estimate the model and then estimate the standard errors of the ratios
*of the coefficients with nlcom (both the weights and the WTP, 

*here, for normalized income
eststo b_`dv'_`countryc'_`fixedeff': reghdfe `depvar' satr1_cont_ppp satr2_cont_ppp democracy public_health effort equal_society if `country'==1, absorb(${`fixedeff'} us france brasil) vce(cluster numericalid) 
estadd local countryt  `country`countryc''
estadd local depvart  `depvar`dv''
eststo a_`dv'_`countryc'_`fixedeff': nlcom $auxbootstrap
estadd local countryt  `country`countryc''
estadd local depvart  `depvar`dv''

*here, with thousands of PPP
eststo b2_`dv'_`countryc'_`fixedeff': reghdfe `depvar' atr1_cont_ppp atr2_cont_ppp democracy public_health effort equal_society if `country'==1, absorb(${`fixedeff'} us france brasil) vce(cluster numericalid) 
estadd local countryt  `country`countryc''
estadd local depvart  `depvar`dv''
eststo a2_`dv'_`countryc'_`fixedeff': nlcom ${auxbootstrap`countryc'}
estadd local countryt  `country`countryc''
estadd local depvart  `depvar`dv''


*Here we estimate them using the same name and then replace, because it's clearer to produce the output with coefplot this way
*First for normalized
capture drop auxincome1 auxincome2
gen auxincome1=satr1_cont_ppp
gen auxincome2=satr2_cont_ppp

eststo plot4a_`dv'_`countryc'_`fixedeff': reghdfe `depvar' auxincome1 auxincome2 democracy public_health effort equal_society if `country'==1, absorb(${`fixedeff'} us france brasil) vce(cluster numericalid) 
estadd local countryt  `country`countryc''
estadd local depvart  `depvar`dv''

*Now replace auxincome for income in PPP and do the same
capture drop auxincome1 auxincome2
gen auxincome1=atr1_cont_ppp
gen auxincome2=atr2_cont_ppp

eststo plot4b_`dv'_`countryc'_`fixedeff': reghdfe `depvar' auxincome1 auxincome2 democracy public_health effort equal_society if `country'==1, absorb(${`fixedeff'} us france brasil) vce(cluster numericalid) 
estadd local countryt  `country`countryc''
estadd local depvart  `depvar`dv''

drop _est_*

}
}
}


********************************************************************************
*****************After having estimated and stored the results,*****************
*****************we will put them into tables and into figures******************
********************************************************************************


*To get the same graphs, you may need to install schemepack, and set this graph scheme
*ssc install schemepack, replace
set scheme white_tableau 
set scheme plotplain
*https://blog.stata.com/2018/10/02/scheming-your-way-to-your-favorite-graph-style/
*https://medium.com/the-stata-guide/stata-schemes-5ef99d099585




**********Here we define a few globals that we use repeatedly in graphs**********

*************************Color patterns by country******************************
global br label(Brazil) mlcolor(midgreen) mfcolor(midgreen) ciopts(color(midgreen))
global fr label(France) mlcolor(blue) mfcolor(blue) ciopts(color(blue))
global us label(US) mlcolor(red) mfcolor(red) ciopts(color(red))

*************************Color patterns by choice/rating*************************
global cho label(Choice (OLS + pair FE)) mlcolor(black) mfcolor(black) ciopts(color(black))
global rat label(Rating (OLS + pair FE)) mlcolor(orange) mfcolor(orange) ciopts(color(orange))


*************************Auxiliary code, AMCE, Weights, WTP*************************
global amce keep(democracy public_health effort equal_society satr1_cont_ppp satr2_cont_ppp) horizontal  coeflabels(satr1_cont_ppp =  "Individual Income"  satr2_cont_ppp = "Country Income"  democracy = "Democracy" public_health = "Public Health" effort = "Effort matters"  equal_society = "Equal Society") order(democracy public_health effort equal_society satr1_cont_ppp satr2_cont_ppp)  xline(0) legend(colfirst rows(1) pos(12))   byopts( rows(1) xrescale)

global amceapp keep(democracy public_health effort equal_society atr1_cont_ppp atr2_cont_ppp) horizontal  coeflabels(atr1_cont_ppp =  "Individual Income (thousands)"  atr2_cont_ppp = "Country Income (thousands)"  democracy = "Democracy" public_health = "Public Health" effort = "Effort matters"  equal_society = "Equal Society") order(democracy public_health effort equal_society atr1_cont_ppp atr2_cont_ppp)  xline(0) legend(colfirst rows(1) pos(12))   byopts( rows(1) xrescale)

global amce4 keep(democracy public_health effort equal_society auxincome1 auxincome2) horizontal  coeflabels(auxincome1 =  "Individual Income"  auxincome2 = "Country Income"  democracy = "Democracy" public_health = "Public Health" effort = "Effort matters"  equal_society = "Equal Society") order(democracy public_health effort equal_society satr1_cont_ppp satr2_cont_ppp)  xline(0) legend(colfirst rows(1) pos(12))   byopts( rows(1) xrescale)
 
global structural keep(ratio1 ratio2 ratio3 ratio4 ratio5 ratio6) horizontal  coeflabels(ratio6 =  "Individual Income"  ratio5 = "Country Income"  ratio1 = "Democracy" ratio2 = "Public Health" ratio3 = "Effort matters"  ratio4 = "Equal Society") order(ratio1 ratio2 ratio3 ratio4 ratio5 ratio6 )  xline(0) legend(colfirst rows(1) pos(12))   byopts( rows(1) xrescale)

global wtp keep(wtp1 wtp2 wtp3 wtp4 wtp5) horizontal  coeflabels( wtp5 = "Country Income" wtp1 = "Democracy" wtp2 = "Public Health" wtp3 = "Effort matters"  wtp4 = "Equal Society") order(wtp1 wtp2 wtp3 wtp4 wtp5 )  xline(0) legend(colfirst rows(1) pos(12))   byopts( rows(1) xrescale )
********************************************************************************

********************************************************************************
**********************************AMCE plots************************************
********************************************************************************
*this plots AMCEs for every country, choice vs. rating, normalized vs. PPP income
coefplot (plot4a_1_2_fe2, $br ) (plot4a_1_3_fe2, $fr ) (plot4a_1_4_fe2, $us ) , bylabel("Choice" "Income: normalized") || /*
*/ (plot4b_1_2_fe2, $br ) (plot4b_1_3_fe2, $fr ) (plot4b_1_4_fe2, $us ) , bylabel("Choice" "Income: $1,000 PPP") || /*
*/  (plot4a_0_2_fe2, $br ) (plot4a_0_3_fe2, $fr ) (plot4a_0_4_fe2, $us ) , bylabel("Rating" "Income: normalized") || /*
*/ (plot4b_0_2_fe2, $br ) (plot4b_0_3_fe2, $fr ) (plot4b_0_4_fe2, $us ) , bylabel("Rating" "Income: $1,000 PPP") || , $amce4  
*paper plot: Fig 1
quietly graph export "${output2}plots/final_amces4.png", as(png) width(1250) replace 
quietly graph export "${output2}plots/final_amces4.pdf", as(pdf) replace 

quietly graph export "${output3}plots/final_amces4.png", as(png) width(1250) replace 
quietly graph export "${output3}plots/final_amces4.pdf", as(pdf) replace

*the next two (amcesrobust) compares AMCEs with and without pair fixed effects, 
*for choice and rating, for either measure of income
coefplot  (b_1_2_fe1, $br ) (b_1_3_fe1, $fr ) (b_1_4_fe1, $us ) , bylabel("Choice" " ") || /*
*/  (b_1_2_fe2, $br ) (b_1_3_fe2, $fr ) (b_1_4_fe2, $us ) , bylabel("Choice +" "Pair Fixed Effects") || /*
*/ (b_0_2_fe1, $br ) (b_0_3_fe1, $fr ) (b_0_4_fe1, $us ) , bylabel("Rating" " ") || /*
*/  (b_0_2_fe2, $br ) (b_0_3_fe2, $fr ) (b_0_4_fe2, $us ) , bylabel("Rating +" "Pair Fixed Effects") || , $amce  
*paper plot: Fig. S4
quietly graph export "${output2}plots/final_amcesrobust.png", as(png) width(1250) replace 
quietly graph export "${output2}plots/final_amcesrobust.pdf", as(pdf) replace 

*paper plot: Fig. S5
coefplot  (b2_1_2_fe1, $br ) (b2_1_3_fe1, $fr ) (b2_1_4_fe1, $us ) , bylabel("Choice" " ") || /*
*/  (b2_1_2_fe2, $br ) (b2_1_3_fe2, $fr ) (b2_1_4_fe2, $us ) , bylabel("Choice +" "Pair Fixed Effects") || /*
*/ (b2_0_2_fe1, $br ) (b2_0_3_fe1, $fr ) (b2_0_4_fe1, $us ) , bylabel("Rating" " ") || /*
*/  (b2_0_2_fe2, $br ) (b2_0_3_fe2, $fr ) (b2_0_4_fe2, $us ) , bylabel("Rating +" "Pair Fixed Effects") || , $amceapp  
quietly graph export "${output2}plots/final_amcesrobust2.png", as(png) width(1250) replace 
quietly graph export "${output2}plots/final_amcesrobust2.pdf", as(pdf) replace 
 
********************************************************************************
***********************************TABLES***************************************
******************************************************************************** 

***************************RELATIVE WEIGHT OF ATTRIBUTES************************
*First we write the code we use repeatedly in globals
global estrw keep(ratio1 ratio2 ratio3 ratio4 ratio5 ratio6)   coeflabels(ratio6 "Individual Income (100\% Increase)" ratio5  "Country Income (100\% increase)"  ratio1   "Democracy" ratio2   "Public Health" ratio3   "Effort matters"  ratio4 "More Equal Society") order(ratio1 ratio2 ratio3 ratio4 ratio5 ratio6 )     

global note addnotes("\footnotesize  Entries are ratios of AMCEs absolute values over the sum of all AMCEs absolute values." "Delta Method standard errors in parenthesis. \sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\)." "AMCEs specification includes individual-specific pair fixed effects and position controls.") substitute(\_ _)

*Here we produce the tables for choice and for rating
*Paper table: Table S5
esttab a_1_2_fe2 a_1_3_fe2 a_1_4_fe2  using "${output2}Tables/final_table_rw_deltamethod_choice.tex", replace $estrw se  mtitles ("Brazil" "France" "US") scalars("depvart Measure of preference")   $note  nonote  
*Paper table: Table 3
esttab a_0_2_fe2 a_0_3_fe2 a_0_4_fe2 using "${output2}Tables/final_table_rw_deltamethod_rating.tex" , replace $estrw se  mtitles ("Brazil" "France" "US") scalars("depvart Measure of preference")   $note  nonote tex


*Here we produce the table for rating again, with slightly different formatting
global note addnotes("\footnotesize  Entries ara AMCEs absolute values over the sum of all AMCEs abso-" "lute values. AMCEs specification includes individual-specific pair fixed" "effects and position controls. Delta Method standard errors in parent-" "hesis. \sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\).") substitute(\_ _)
*Paper table (the same but with another formatting)
esttab a_0_2_fe2 a_0_3_fe2 a_0_4_fe2 using "${output3}Tables/final_table_rw_deltamethod_rating.tex" , replace $estrw se  b(3) se(3)  mtitles ("Brazil" "France" "US") scalars("depvart Measure of preference")   $note  nonote tex varwidth(20) wrap


*************************************WTP****************************************

*Again, we write the code in globals whenever it is useful to reuse it 
*TABLES
global estwtp keep(wtp1 wtp2 wtp3 wtp4 wtp5)   coeflabels( wtp5  "10\% increase in Country Income"  wtp1   "Democracy" wtp2   "Public Health" wtp3   "Effort matters"  wtp4   "More Equal Society") order(wtp1 wtp2 wtp3 wtp4 wtp5 )     

global note addnotes("\footnotesize  Entries are ratios of AMCEs. Delta Method standard errors in parenthesis. ACMEs estimated with individual-level pair fixed" "effects and position controls. Columns 1-3: WTP as a percentage of the average income. Columns 4-6: WTP in thousands" "of PPP\textdollar. \sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\).") substitute(\_ _)

*This produces the tables of WTP for choice and rating
*Paper table: Table S4
esttab a_1_2_fe2 a_1_3_fe2 a_1_4_fe2 a2_1_2_fe2 a2_1_3_fe2 a2_1_4_fe2 using "${output2}Tables/final_table_wtp_deltamethod_all_choice.tex"  , replace $estwtp se mgroups("WTP for normalized income"  "WTP and income in \\$1,000 PPP", pattern(1 0 0 1 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))  mtitles("Brazil" "France" "US" "Brazil" "France" "US") scalars("depvart Measure of preference")   $note  nonote  tex
*Paper table: Table 2
esttab a_0_2_fe2 a_0_3_fe2 a_0_4_fe2 a2_0_2_fe2 a2_0_3_fe2 a2_0_4_fe2 using "${output2}Tables/final_table_wtp_deltamethod_all_rating.tex"  , replace $estwtp se mgroups("WTP for normalized income"  "WTP and income in \\$1,000 PPP", pattern(1 0 0 1 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))  mtitles("Brazil" "France" "US" "Brazil" "France" "US") scalars("depvart Measure of preference")   $note  nonote  tex

global note2 addnotes("\footnotesize Entries are ratios of AMCEs. ACMEs estimated with individual-specific pair fixed effects and position controls. Delta" "Method standard errors in parenthesis.  \sym{*} \(p<0.10\),\sym{**} \(p<0.05\), \sym{***} \(p<0.01\). Columns 1-3: WTP as a percent-" "age of the average country income. Columns 4-6: WTP in thousands of PPP\textdollar.") substitute(\_ _)

*Again here we have the same tables (Table S4 and Table 2) but another formatting
*Paper table
esttab a_1_2_fe2 a_1_3_fe2 a_1_4_fe2 a2_1_2_fe2 a2_1_3_fe2 a2_1_4_fe2 using "${output3}Tables/final_table_wtp_deltamethod_all_choice.tex"  , replace $estwtp se b(3) se(2)   mgroups("WTP for normalized income"  "WTP and income in \\$1,000 PPP", pattern(1 0 0 1 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))  mtitles("Brazil" "France" "US" "Brazil" "France" "US") scalars("depvart \shortstack{Measure of\\ preference}")   nonote  tex varwidth(15) wrap     
*Paper table
esttab a_0_2_fe2 a_0_3_fe2 a_0_4_fe2 a2_0_2_fe2 a2_0_3_fe2 a2_0_4_fe2 using "${output3}Tables/final_table_wtp_deltamethod_all_rating.tex"  , replace $estwtp se b(3) se(2)    mgroups("WTP for normalized income"  "WTP and income in \\$1,000 PPP", pattern(1 0 0 1 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))  mtitles("Brazil" "France" "US" "Brazil" "France" "US") scalars("depvart \shortstack{Measure of\\ preference}")   $note2  nonote  tex  varwidth(15) wrap   


 
********************************************************************************
***************************Individual-level analyis*****************************
********************************************************************************


*We use asreg to compute individual-level coefficients,
*from which we can compute individual level weights

*For choice
bys numericalid: asreg choice democracy effort satr1_cont_ppp satr2_cont_ppp public_health equal_society, robust
foreach var in _Nobs _R2 _adjR2 _b_democracy _b_effort _b_satr1_cont_ppp _b_satr2_cont_ppp _b_public_health _b_equal_society _b_cons _se_democracy _se_effort _se_satr1_cont_ppp _se_satr2_cont_ppp _se_public_health _se_equal_society _se_cons{
rename `var' c`var'
}
*For rating
bys numericalid: asreg rating democracy effort satr1_cont_ppp satr2_cont_ppp public_health equal_society , robust
foreach var in _Nobs _R2 _adjR2 _b_democracy _b_effort _b_satr1_cont_ppp _b_satr2_cont_ppp _b_public_health _b_equal_society _b_cons _se_democracy _se_effort _se_satr1_cont_ppp _se_satr2_cont_ppp _se_public_health _se_equal_society _se_cons{
rename `var' r`var'
}
*And we compute the weights
foreach var in c r{
gen `var'structural_denominator=(abs(`var'_b_democracy)+abs(`var'_b_public_health)+abs(`var'_b_effort)+abs(`var'_b_equal_society)+abs(`var'_b_satr1_cont_ppp)+ /*
*/ abs(`var'_b_satr2_cont_ppp))

foreach cvar in democracy public_health effort equal_society satr1_cont_ppp satr2_cont_ppp{
gen `var's_`cvar'=`var'_b_`cvar'/`var'structural_denominator
}
}

*We do the same individual-regressions with normalized and thousands of ppp dollars

bys numericalid: asreg choice democracy effort atr1_cont_ppp atr2_cont_ppp public_health equal_society, robust
foreach var in _Nobs _R2 _adjR2 _b_democracy _b_effort _b_atr1_cont_ppp _b_atr2_cont_ppp _b_public_health _b_equal_society _b_cons _se_democracy _se_effort _se_atr1_cont_ppp _se_atr2_cont_ppp _se_public_health _se_equal_society _se_cons{
rename `var' cppp`var'
}
bys numericalid: asreg rating democracy effort atr1_cont_ppp atr2_cont_ppp public_health equal_society , robust
foreach var in _Nobs _R2 _adjR2 _b_democracy _b_effort _b_atr1_cont_ppp _b_atr2_cont_ppp _b_public_health _b_equal_society _b_cons _se_democracy _se_effort _se_atr1_cont_ppp _se_atr2_cont_ppp _se_public_health _se_equal_society _se_cons{
rename `var' rppp`var'
}


*To compute standard errors of individual-level weights we need reg and nlcome

egen group_nid=group(numericalid)
gen se_demc=.
gen se_demr=.  
forval z=1(1)5227{
*For rating and choice
quietly reg rating  satr1_cont_ppp satr2_cont_ppp democracy public_health effort equal_society  if group_nid==`z', robust
capture nlcom ((_b[democracy]/((abs(_b[satr1_cont_ppp])+abs(_b[satr2_cont_ppp])+abs(_b[democracy]))+abs(_b[public_health])+abs(_b[effort])+abs(_b[equal_society])))), post
capture replace se_demr=_se[_nl_1] if group_nid==`z'
quietly reg choice  satr1_cont_ppp satr2_cont_ppp democracy public_health effort equal_society  if group_nid==`z', robust
capture nlcom ((_b[democracy]/((abs(_b[satr1_cont_ppp])+abs(_b[satr2_cont_ppp])+abs(_b[democracy]))+abs(_b[public_health])+abs(_b[effort])+abs(_b[equal_society])))), post
capture replace se_demc=_se[_nl_1] if group_nid==`z'
}


*Here we can choose to save an intermediate dataset, because this last bit is a little slow to run
*save Data/final_auxnlcom_pnas.dta, replace
*clear all
*use Data/final_auxnlcom_pnas.dta


*******************Plot of percentiles of of individual weights*****************
bys numericalid: gen n=_n
bys pais: gen auxplot=_n
gen quant2=.
gen index2=.

foreach pais in brasil france us{
qrprocess rs_democracy if n==1 & `pais'==1, quantile(0.01(0.01).99)
matrix quant=e(b)
matrix index=e(quantiles)
forval z=1(1)102{
replace quant2=quant[1,`z'] if auxplot==`z' & `pais'==1
replace index2=index[`z',1]*100 if auxplot==`z' & `pais'==1
}
}

twoway (line quant2 index2 if brasil==1, color(green) lwidth(thick) legend(label( 1 "Brasil")))   (line quant2 index2 if france==1, lwidth(thick) color(blue)  legend(label( 2 "France")))  (line quant2 index2  if us==1, color(red) lwidth(thick)  legend(label( 3 "US") rows(1) pos(6))  ytitle("Weight of democracy") xtitle("Percentile") ylabel(-.4(.2)1) xlabel(1 10 20 30 40 50 60 70 80 90 99)  yline(0)) 

set scheme white_tableau 

*paper plot: Fig. S8
quietly graph export "${output3}plots/final_percentiles.pdf", as(pdf)   replace
quietly graph export "${output2}plots/final_percentiles.pdf", as(pdf)   replace

drop quant2 index2 auxplot  
set scheme plotplain
********************************************************************************







**************************Plots of distributions*******************************

*We create these variables that we'll fill later and use to classify people 
*as a function of their weight of democracy
gen canti_democracy=0
gen cmid_democracy=0
gen cpro_democracy=0
gen cwanti_democracy=0
gen cwmid_democracy=0
gen cwpro_democracy=0
gen ranti_democracy=0
gen rmid_democracy=0
gen rpro_democracy=0
gen rwanti_democracy=0
gen rwmid_democracy=0
gen rwpro_democracy=0

*Winsorizing for inverse variance weight plots
gen rvar_demr=1/(se_demr^2) if se_demr>0.0001
egen minw=min(rvar_demr), by(pais)
replace rvar_demr=minw if se_demr<=0.0001

*We do it separately by country
foreach country in all brasil france us{

local colorall black
local colorbrasil green
local colorfrance blue
local colorus red
local titleall All
local titlebrasil Brazil
local titlefrance France
local titleus US

*Plot for choices
sum cs_democracy if `country'==1 & n==1, d
local median`country' `r(p50)'
local mean`country' `r(mean)'
*We classify people depending on whether their weight is negative or zero, 
*between zero and the median, or above the median
replace canti_democracy=1 if cs_democracy<=0 & `country'==1
replace cmid_democracy=1 if cs_democracy>0 & cs_democracy<=`median`country'' & `country'==1
replace cpro_democracy=1 if cs_democracy>0 & cs_democracy>`median`country'' & `country'==1
*store the plot for every country, we will later combine the three of them
twoway (kdensity cs_democracy if `country'==1, xline(`median`country'' `mean`country'') xlabel(-1 -0.5 0 0.5 `r(p50)' "Median" `r(mean)' "Mean" 1, angle(45) alternate) ytitle(" ") xtitle(" ") lcolor(`color`country'') subtitle("`title`country'' "))  , name(a11`country', replace)

*Plot for rating
sum rs_democracy if `country'==1 & n==1, d
local median`country' `r(p50)'
local mean`country' `r(mean)'
*We classify people depending on whether their weight is negative or zero, 
*between zero and the median, or above the median
replace ranti_democracy=1 if rs_democracy<=0 & `country'==1
replace rmid_democracy=1 if rs_democracy>0 & rs_democracy<=(`median`country'') & `country'==1
replace rpro_democracy=1 if rs_democracy>0 & rs_democracy>(`median`country'') & `country'==1
*store the plot for every country, we will later combine the three of them
twoway (kdensity rs_democracy if `country'==1, xline(`median`country'' `mean`country'') xlabel(-1 -0.5 0 0.5 `r(p50)' "Median" `r(mean)' "Mean" 1, angle(45) alternate) ytitle(" ") xtitle(" ") lcolor(`color`country'') subtitle(" `title`country'' "))  , name(a22`country', replace)

*Plot with weighting
sum rs_democracy if `country'==1 & n==1 [aweight=rvar_demr], d
local median`country' `r(p50)'
local mean`country' `r(mean)'
*We classify people depending on whether their weight is negative or zero, 
*between zero and the median, or above the median
replace rwanti_democracy=1 if rs_democracy<=0 & `country'==1
replace rwmid_democracy=1 if rs_democracy>0 & rs_democracy<=(`median`country'') & `country'==1
replace rwpro_democracy=1 if rs_democracy>0 & rs_democracy>(`median`country'') & `country'==1
*store the plot for every country, we will later combine the three of them
twoway (kdensity rs_democracy if `country'==1 [aweight=rvar_demr], xline(`median`country'' `mean`country'') xlabel(-1 -0.5 0 0.5 `r(p50)' "Median" `r(mean)' "Mean" 1, angle(45) alternate) ytitle(" ") xtitle(" ") lcolor(`color`country'') subtitle(" `title`country'' "))  , name(a3`country', replace)



}

*Combine graphs and save them:

*Paper plot: Fig 2
graph combine a22brasil a22france a22us, xcommon ycommon rows(1)  
quietly graph export "${output3}plots/final_density_structural_horizontal.pdf", as(pdf)   replace
quietly graph export "${output2}plots/final_density_structural_horizontal.pdf", as(pdf)   replace

*Paper plot: Fig S7
graph combine a11brasil a11france a11us, xcommon ycommon rows(1)  
quietly graph export "${output3}plots/final_density_structural_horizontal_appendix.pdf", as(pdf)   replace
quietly graph export "${output2}plots/final_density_structural_horizontal_appendix.pdf", as(pdf)   replace

*Paper plot: Fig S6
graph combine a3brasil a3france a3us, xcommon ycommon rows(1)  
quietly graph export "${output3}plots/final_density_structural_horizontal_appendix2.pdf", as(pdf)   replace
quietly graph export "${output2}plots/final_density_structural_horizontal_appendix2.pdf", as(pdf)   replace


************************CHARACTERISTICS OF PRO VS. ANTI DEM*********************
*Recode the pro-moderate-anti variables
foreach s in c r{
capture drop `s'antipro
gen `s'antipro=1 if `s'anti_democracy==1
replace `s'antipro=2 if `s'mid_democracy==1
replace `s'antipro=3 if `s'pro_democracy==1
}

*List of variables for E[X|Pro/Mod/Anti]
global balancevars income_above veryhigh_income wealthy_hh wealthy_parents college high_school age female smachiavelism_all snarcissism_all spsychopathy_all pol_right_wing pol_pro_trade pol_immig pol_tech status

label define dem 1 "Non-Democratic" 2 "Moderate Pro-Dem" 3 "Pro-Democracy" , replace
label values cantipro dem
label values rantipro dem

*create auxiliary variables for balancetable pairwise differences 
gen deltar12=1 if rantipro==2
replace deltar12=0 if rantipro==1
gen deltar23=1 if cantipro==2
replace deltar23=0 if cantipro==3

set scheme white_tableau
foreach country in brasil france us{
*Paper table: Table S6, S7, S8
balancetable (mean if rantipro==1 & n==1 & `country'==1) (mean if rantipro==2 & n==1 & `country'==1) (mean if rantipro==3 & n==1 & `country'==1) (diff deltar12 if n==1 & `country'==1 & deltar12!=.) (diff deltar23 if n==1 & `country'==1 & deltar23!=.) $balancevars using "${output2}Tables/final_balancer_antiprodem_`country'.tex" , replace ctitles("Non-Dem$^{\dagger}$" "Moderate Pro-Dem$^{\ddagger}$" "Pro-Dem$^{\mathsection}$" "Moderate vs. Non" "Moderate vs. Pro") varlabels   groups("Means across democracy weight groups" "Differences across groups", pattern(1 0 0 1 0) end("\cmidrule(lr){2-4} \cmidrule(lr){5-6}" )) postfoot("\hline" "\multicolumn{6}{p{.825\linewidth}}{Columns 1 to 3 report mean values of covariates and standard deviations in parenthesis, splitting survey participants based on their individual weight of democracy, measured from ratings. $\dagger$ Non-Dem: negative or zero weight. $\ddagger$ Moderate Pro-Dem: positive but below or equal to the median weight.  $\mathsection$ Pro-Dem: positive and above the median. Columns 4 and 5 report differences between columns 1 and 2 and between columns 2 and 3, respectively. Standard errors are in parenthesis and \sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***}. High income: household income above the country monthly average (3000 reals/euro, or 6000 USD). Very high income: monthly household income above 5000 reals/euro 5000, or 9000 USD). Machavellianism, narcissism and psychopathy are standardized to have mean zero and standard deviation of one, from the sum of scores in 5 questions. Status $>$ Concrete is the 2nd principal component of the responses to debriefing questions about income motivations in answering the conjoint, which features positive weights for status motivations for income and negative weights for material motivations for income.}" /*
*/ "\end{tabular}"  )
}




****************************Covariate balance tables****************************

gen indiv_income_high=atr1>3
replace indiv_income_high=. if atr1==3
gen country_income_high=atr1>2
replace country_income_high=. if atr2==2

*Paper tables: Table S1, S2, S3
foreach country in brasil france us{
balancetable (diff democracy if `country'==1) (diff public_health if  `country'==1) (diff effort if `country'==1) (diff equal_society if  `country'==1) (diff indiv_income_high if  `country'==1) (diff country_income_high if `country'==1) $balancevars using "${output2}Tables/final_balance_covars_`country'.tex" , replace vce(robust)  ctitles("Democracy" "Public Health" "Effort" "Equal Society" "High I. Income" "High C. Income") varlabels   groups("E[Covariate | Treatment = 1] - E[Covariate | Treatment = 0]", pattern(1 0 0 0 0) end("\cmidrule(lr){2-7}"))  postfoot("\hline" "\multicolumn{7}{p{.85\linewidth}}{Robust standard errors in parenthesis. \sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\). High I. Income: individual income treatment above the country monthly average. High C. Income: country income treatment above the country average. High income: household income above the country monthly average (3000 reals/euro, or 6000 USD). Very high income: monthly household income above 5000 reals/euro 5000, or 9000 USD). Machavellianism, narcissism and psychopathy are standardized to have mean zero and standard deviation of one, from the sum of scores in 5 questions. Status $>$ Concrete is the 2nd principal component of the responses to debriefing questions about income motivations in answering the conjoint, which features positive weights for status motivations for income and negative weights for material motivations for income.}" /*
*/ "\end{tabular}"  )
}

drop indiv_income_high country_income_high







********************************************************************************
*******************************FLIPPING DEMOCRACY*******************************
********************************************************************************

*Create variables that we're going to fill:
gen increment=.

gen flip_r_ii=.
gen flipi_r_ii=.

gen flip_rl_ii=.
gen flipi_rl_ii=.

*We compute the percentage supporting democracy by creating individual dummies
*of against/in favor, and use the loop for various iincome increases
local i=0
foreach z in 0 0.1 0.3 0.5 1 3 5{
local i=`i'+1

local w=`z'*10

gen flip_r_ii`w'=1-((r_b_satr2_cont_ppp*`z'+r_b_satr1_cont_ppp*`z') > r_b_democracy) if n==1

replace flip_r_ii=1-((r_b_satr2_cont_ppp*`z'+r_b_satr1_cont_ppp*`z') > r_b_democracy) if n==`i'

gen flipi_r_ii`w'=1-((r_b_satr1_cont_ppp*`z') > r_b_democracy) if n==1

replace flipi_r_ii=1-(r_b_satr1_cont_ppp*`z' > r_b_democracy) if n==`i'


replace increment=`w'*10 if n==`i'

label var flip_r_ii`w' "Income x `w'0 %"
}

binscatter flipi_r_ii increment, linetype(connect) yline(0.5, lwidth(thick))  by(pais) ylabel(0.4(0.2).8) colors(green blue red) symbols(circle square diamond) legend(label (1 "Brazil") label(2 "France") label(3 "US")) ytitle("Predicted Support for Democracy") xtitle("Income increase (percentage)") subtitle("Individual Income Increase") name(a1, replace) legend(ring(0) pos(2)) discrete

binscatter flip_r_ii increment, linetype(connect) yline(0.5, lwidth(thick))  by(pais) ylabel(0.4(0.2).8) colors(green blue red) symbols(circle square diamond) legend(label (1 "Brazil") label(2 "France") label(3 "US")) ytitle("Predicted Support for Democracy") xtitle("Income increase (percentage)") subtitle("Individual and Country Income Increase") name(a2, replace) legend(ring(0) pos(2)) discrete

  
graph combine a1 a2, rows(1) 

*Paper plot: top panel, Fig 3
quietly graph export "${output2}plots/final_income_decay_rating.pdf", as(pdf)   replace
quietly graph export "${output3}plots/final_income_decay_rating.pdf", as(pdf)   replace


 
********************************************************************************
************************HERE WE COMBINE INSTITUTIONS AND INCOME*****************
********************************************************************************

capture drop n
capture drop increment
bys numericalid: gen n=_n
gen increment=.
capture drop flip_r
gen flip_r=.
local i=1


replace flip_r=1-(0>r_b_democracy) if n==`i'

local i=`i'+1
replace flip_r=1-((r_b_public_health) > r_b_democracy) if n==`i'

local i=`i'+1
replace flip_r=1-((r_b_public_health+r_b_effort) > r_b_democracy)  if n==`i'


local i=`i'+1
replace flip_r=1-((r_b_public_health+r_b_effort+r_b_equal_society) > r_b_democracy)  if n==`i'

 
local i=`i'+1
replace flip_r=1-((r_b_public_health+r_b_effort+r_b_equal_society+r_b_satr2_cont_ppp*0.5+r_b_satr1_cont_ppp*0.5) >r_b_democracy )  if n==`i'

local i=`i'+1
replace flip_r=1-((r_b_public_health+r_b_effort+r_b_equal_society+r_b_satr2_cont_ppp+r_b_satr1_cont_pp) > r_b_democracy)  if n==`i'

local i=`i'+1
replace flip_r=1-((r_b_public_health+r_b_effort+r_b_equal_society+r_b_satr2_cont_ppp*2+r_b_satr1_cont_ppp*2) > r_b_democracy)  if n==`i'

local i=`i'+1
replace flip_r=1-((r_b_public_health+r_b_effort+r_b_equal_society+r_b_satr2_cont_ppp*3+r_b_satr1_cont_ppp*3) > r_b_democracy)  if n==`i'


replace n=10 if n==8
replace n=8  if n==7

*paper plot:  bottom panel, Fig 3
binscatter flip_r n , linetype(connect) yline(0.5, lwidth(thick))  by(pais) ylabel(0.3(0.1).8)  colors(green blue red) legend(label (1 "Brazil") label(2 "France") label(3 "US")) ytitle("Predicted Support for Democracy") xtitle(" ")   name(a1, replace) legend(ring(0) pos(2)) discrete xlabel(1 "All Equal" 2 "+Public Health" 3 "+...+Effort" 4 "+...+Equal Society"  5 "+...+50% Income" 6 "+...+100% Income" 8 "+...+200% Income" 10 "+...+300% Income", angle(45)) note("Note: monthly income increase for both country and individual income. All other features held constant unless otherwise stated." "Preference measurement: ratings.", size(vsmall))
quietly graph export "${output2}plots/final_all_decay_rating.pdf", as(pdf)   replace
quietly graph export "${output3}plots/final_all_decay_rating.pdf", as(pdf)   replace




 



